package yml

import (
	"github.com/spf13/viper"
	"strings"
)

const (
	defaultFolder = "config"
	defaultType   = "yml"
)

type Config struct {
	viper *viper.Viper
}

func GenerateYamlByFile(fileName string) (*Config, error) {
	yc := viper.New()
	yc.AddConfigPath(defaultFolder)
	yc.SetConfigName(fileName)
	yc.SetConfigType(defaultType)

	if err := yc.ReadInConfig(); err != nil {
		return nil, err
	}
	return &Config{
		yc,
	}, nil
}

func GenerateYamlByStr(source string) (*Config, error) {
	yc := viper.New()

	yc.SetConfigType(defaultType)
	if err := yc.ReadConfig(strings.NewReader(source)); err != nil {
		return nil, err
	}
	return &Config{
		yc,
	}, nil
}

func (y Config) Get(key string) interface{} {
	return y.viper.Get(key)
}

func (y Config) GetString(key string) string {
	return y.viper.GetString(key)
}

func (y Config) GetInt(key string) int {
	return y.viper.GetInt(key)
}

func (y Config) GetBool(key string) bool {
	return y.viper.GetBool(key)
}

func (y Config) GetStringSlice(key string) []string {
	return y.viper.GetStringSlice(key)
}

func (y Config) GetEntity(entity interface{}) error {
	return y.viper.Unmarshal(entity)
}

func (y Config) GetChildEntity(key string, entity interface{}) error {
	return y.viper.UnmarshalKey(key, entity)
}
